// 2804跳转
const jumpBy2804 = (url: string): void => {
  if (!url || typeof url !== 'string') {
    return;
  }
  if (!url.includes('client.html')) {
    !url.startsWith('http') && (url = location.protocol + url);
    location.href = `client://client.html?action=ymtz^webid=2804^mode=new^url=${url}`;
  } else {
    location.href = url;
  }
};
// 错误上报
const errorReport = (error: { name: string; message: string; stack: string }) => {
  if (!window?.ClientMonitor?.reportFrameErrors) {
    return;
  }
  window.ClientMonitor.reportFrameErrors(
    {
      category: 'js',
      grade: 'Error'
    },
    {
      name: error.name,
      message: error.message,
      stack: error.stack
    }
  );
};

// 金额单位换算
const unitConvertFun = (
  num: number,
  retainDecimal: boolean = false
): string | { value: number; unit: string } => {
  const moneyUnits = [
    { base: 1, unit: '' },
    { base: 10000, unit: '万' },
    { base: 100000000, unit: '亿' }
  ];
  let currentNum: number | string = num;
  // 设置默认单位换算下标
  let currentUnitIndex = 0;
  // 判断区间获取对应单位
  for (let i = 0; i < moneyUnits.length; i++) {
    if (!moneyUnits[i + 1]) {
      currentUnitIndex = moneyUnits.length - 1;
      break;
    } else if (
      Math.abs(currentNum) >= moneyUnits[i].base &&
      Math.abs(currentNum) < moneyUnits[i + 1].base
    ) {
      currentUnitIndex = i;
      break;
    }
  }
  if (Math.abs(currentNum) < 10000) {
    return retainDecimal ? { value: currentNum, unit: '' } : currentNum.toFixed(2);
  } else {
    // 计算值
    currentNum = currentNum / moneyUnits[currentUnitIndex].base;
    if (!retainDecimal) {
      currentNum = currentNum.toFixed(2);
      return currentNum + moneyUnits[currentUnitIndex].unit;
    } else {
      return {
        value: currentNum,
        unit: moneyUnits[currentUnitIndex].unit
      };
    }
  }
};

//无数据情况处理，传入空字符串
const judgeIsNull = function (val: unknown) {
  const target = typeof val === 'object' ? Object.prototype.toString.call(val) : `${val}`;
  if (/null|undefined|nan|^\s*$/i.test(target)) {
    return '--';
  }
  return val;
};

//位数转换（元、万、亿）
const unitConvert = function (val) {
  if (judgeIsNull(val) === '--') {
    return '--';
  } else {
    return unitConvertFun(val);
  }
};

//数字处理，可配置isDecimal：是否保留两位小数、isPositive：是否增加%、isPercent：是否增加正号
const numberFormat = function (
  val: string,
  isDecimal: boolean | number,
  isPositive: boolean,
  isPercent: boolean = false
): string {
  if (judgeIsNull(val) === '--') {
    return '--';
  }
  const currentVal = parseFloat(val);
  let resultVal: string | number = parseFloat(val);
  if (isDecimal && String(isDecimal) !== 'true') {
    resultVal = resultVal.toFixed(isDecimal as number);
  } else if (isDecimal) {
    resultVal = resultVal.toFixed(2);
  }
  resultVal = isPositive ? `${resultVal}%` : resultVal;
  resultVal = isPercent && currentVal > 0 ? `+${resultVal}` : resultVal;
  return resultVal as string;
};

const matchValueFormat = (value: string, type: string) => {
  if (['percent', 'number'].includes(type)) {
    return numberFormat(value, true, type === 'percent');
  } else if (type === 'money') {
    return unitConvert(value);
  } else {
    return judgeIsNull(value);
  }
};

const matchStrchangeHTML = (
  str: string,
  moduleType: 'good' | 'bad' | 'suggest',
): null | string => {
  if (!str) {
    return null;
  }
  const regExp = new RegExp(/\$\{(text|percent|number|integer|money|date)\|.*?\}/g);
  const formatStr = str.replace(regExp, (item) => {
    const matchValue = item.replace('${', '').replace('}', '');
    const value = matchValue.split('|')[1];
    const type = matchValue.split('|')[0];
    const isRed = ['percent', 'number', 'integer'].includes(type) && moduleType === 'good';
    const isGreen = ['percent', 'number', 'integer'].includes(type) && moduleType === 'bad';
    return `<span class="${isRed ? 'red' : ''} ${isGreen ? 'green' : ''}">${matchValueFormat(
      value,
      type
    )}</span>`;
  });
  return formatStr;
};

export { jumpBy2804, errorReport, matchStrchangeHTML };
